const Router = require('koa-router');
const router = new Router();

router.get('/all2', async ctx => {
    const { getWorksTypeAll, getWorksTypeAll2 } = require('../models/worksType');
    const res_1 = (await getWorksTypeAll(ctx.access_token))
    ctx.errcode(res_1.data.errcode, res_1.data.errmsg)
    const res_2 = (await getWorksTypeAll2(ctx.access_token))
    ctx.errcode(res_2.data.errcode, res_2.data.errmsg)
    
    const res = res_1.data.data.map(item => JSON.parse(item)).map(res1_item => {
        res1_item.children = []
        res_2.data.data.map(item => JSON.parse(item)).forEach(item2 => {
            if(item2.parentId === res1_item._id) {
                res1_item.children.push(item2)   
            }
        })
        return res1_item
    })

    ctx.body = {
        code: 200,
        data: res,
        msg: 'ok'
    };
})
router.get('/all', async ctx => {
    const { getWorksTypeAll } = require('../models/worksType');
    const res = await getWorksTypeAll(ctx.access_token)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data.data.map(item => JSON.parse(item)),
        msg: 'ok'
    };
})
router.get('/', async ctx => {
    const { getWorksType } = require('../models/worksType');
    const res = await getWorksType(ctx.access_token, ctx.query)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: {
            ...res.data,
            data: res.data.data.map(item => JSON.parse(item)),
        },
        msg: 'ok'
    };
})
router.get('/:id', async ctx => {
    const { getInfo } = require('../models/worksType');
    const res = await getInfo(ctx.access_token, ctx.params.id)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: (res.data.data.map(item => JSON.parse(item)))[0],
        msg: 'ok'
    };
})
router.post('/', async ctx => {
    const { addWorksType } = require('../models/worksType');
    const res = await addWorksType(ctx.access_token, ctx.request.body)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data,
        msg: 'ok'
    };
})
router.delete('/', async ctx => {
    const { delWorksType } = require('../models/worksType');
    const res = await delWorksType(ctx.access_token, ctx.query.id)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data,
        msg: 'ok'
    };
})
router.put('/', async ctx => {
    const { updateWorksType } = require('../models/worksType');
    const res = await updateWorksType(ctx.access_token, ctx.request.body)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data,
        msg: 'ok'
    };
})

module.exports = router.routes();